package zyy;


import java.io.*;
import java.util.*;

public class zy {
    public static void main(String[] args) {
        File file = new File("C:\\Users\\21939\\Desktop\\商品列表.txt");
        int count = 0;
        double sum = 0;
        Set<Double> uniquePrices = new HashSet<>(); // 使用 Set 存储独特价格

        try (Scanner sc = new Scanner(file)) {
            sc.useDelimiter("[，/台]+"); // 使用正则表达式分隔商品名称和价格

            while (sc.hasNext()) {
                String product = sc.next(); // 读取商品名称
                if (sc.hasNextDouble()) {
                    double price = sc.nextDouble(); // 读取价格
                    if (uniquePrices.add(price)) { // 如果是新价格，才加入
                        count++;
                        sum += price;
                        System.out.println("商品: " + product + " 价格: " + (int) price + " /台");
                    }
                }
            }

            // 计算并打印平均价格
            if (count > 0) {
                double average = sum / count;
                String averageStr = String.format("%.1f", average);
                System.out.println("平均价格: " + averageStr + " /台");

                // 将平均价格追加写入文件
                try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) {
                    bw.write("平均价格: " + averageStr + " /台\n");
                    System.out.println("平均价格已写入文件。");
                }
            } else {
                System.out.println("未找到价格数据。");
            }

        } catch (FileNotFoundException e) {
            System.out.println("文件未找到: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("写入文件时发生错误: " + e.getMessage());
        }
    }
}
